<!--
 * @Author: Liujingjing
 * @Date: 2022-01-08 19:50:01
 * @LastEditTime: 2022-01-10 22:49:07
 * @LastEditors: Liujingjing
 * @Description: 
 * @FilePath: \am\am-ui\src\pages\extend\Role.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->
<template>
  <div class="device">
    <!-- 角色管理 -->
    <div class="header">
      

      <el-input
        placeholder="请输入内容"
        v-model="inputVal"
        clearable
        style="width: 180px"></el-input>

      <el-button type="success" style="margin: 0 10px">搜索</el-button>
      <el-button type="success" style="float: right" @click="showDrawer">录入</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column
        type="index"
        :index="1"
        label="序号"
        width="90"
        align="center">
      </el-table-column>
      
      <el-table-column prop="name" label="角色名称" min-width="100" align="center">
      </el-table-column>
      <el-table-column label="操作" min-width="100" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click.prevent="toAuthorization(scope.row)">授权</el-button>
          <el-button type="text" @click="editBtn(scope.row)">修改</el-button>
          <el-button type="text" @click="deletBtn(scope.row.id)" style="color: red">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
      size="50%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        style="padding: 10px">
        
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 授权模态框 -->
    <el-dialog title="授权" :visible.sync="authorization_visible" width="80%">
      <el-form :model="role">
        <!-- {{role}} -->
        <el-form-item label="角色名称" prop="name" label-width="80px">{{ role.name }}</el-form-item>
        <el-form-item label="权限" label-width="80px">
          <el-cascader-panel
            v-model="role.privileges"
            :options="options"
            :props="{ multiple: true, checkStrictly: true ,emitPath:false}"
            clearable
            @change="handler"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="authorization_visible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="authorizationHandler">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { get, postJSON ,del,post} from "../../utils/request";
export default {
  data() {
    return {
      authorization_visible: false,
      role: {}, // 当前角色
      result: [],
      props: {
        multiple: true,
        value: "id",
        label: "name",
        emitPath: false,
        checkStrictly: true
      },
      options: [],
      
      inputVal: "",
      tableData: [],
      drawer: false,
      ruleForm: {
        name: "",
        id: "",
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      title: "",
    };
  },
  created() {
    this.getDeviceList();
    // 加载权限
    this.loadPrivileges();
  },
  methods: {
    //查询角色列表
    getDeviceList() {
      get("/role/findAll", {
        name: "",
      }).then(res => {
        if (res && res.status == 200 && res.data ) {
          this.tableData = res.data;
          // 将权限转换为id的数组
          this.result = this.tableData.map(item => {
          return item.id;
        });
          console.log(334433,res)
        } else {
          this.tableData = [];
          console.log(2134,res)
        }
      });
    },
    //修改角色信息
    editBtn(row) {
      console.log(7777,row)
      this.drawer = true;
      this.title = "修改角色信息";
      this.ruleForm = {
        name:row.name,
        id:row.id,
      };
    },
    //添加保存或更新角色
    addDevice() {
      postJSON("/role/saveOrUpdate", this.ruleForm).then(
        res => {
          console.log(8888, res);
        }
      );
    },
    //删除
    deletBtn(id){
      del('/role/deleteById',{
        id:id
      }).then(res=>{
        console.log(6666,res)
        if(res && res.status == 200){
          this.$notify({
                title: '成功',
                message: '设备角色删除成功',
                type: 'success'
              });
              this.getDeviceList()
        }else{
          this.$notify.error({
                title: "警告",
                message: "设备角色删除失败",
              });
        }
      })
    },
    //打开抽屉
    showDrawer() {
      this.drawer = true;
      this.title = "添加角色信息";
      this.ruleForm = {};
    },
    //关闭抽屉
    handleClose(done) {
      done();
      // this.$refs[ruleForm].resetFields();
    },
    //提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          postJSON(
            "/role/saveOrUpdate",
            this.ruleForm
          ).then(res => {
            console.log(8888, res);
            if (res && res.status == 200) {
              if (this.ruleForm.id) {
                this.$notify({
                  title: "成功",
                  message: "设备角色修改成功",
                  type: "success",
                });
              } else {
                this.$notify({
                title: '成功',
                message: '设备角色添加成功',
                type: 'success'
              });
              }
              this.drawer = false;
              this.getDeviceList()
            } else {
              this.$notify.error({
                title: "错误",
                message: "设备角色添加失败",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  
// 去授权
    toAuthorization(record) {
      get("/role/findPrivilegesById", { id: record.id }).then(res => {
        let result = [];
        res.data.forEach(item => {
          let obj = {};
          obj.value = item.id;
          obj.label = item.name;
          result.push(obj);
        });
        let result1 = result.map(item => {
          return item.value;
        });
        record.privileges = result1;
        this.role = record;
      });
      
      this.authorization_visible = true;
    },
    // 获取权限树
  loadPrivileges() {
      get("/privilege/findPrivilegeTree").then(res => {
        let arr = res.data;
        let options = [];
        res.data.forEach(item => {
          let obj = {};
          obj.value = item.id;
          obj.label = item.name;
          obj.children = item.children.map(i => {
            return {
              value: i.id,
              label: i.name
            };
          });
          options.push(obj);
        });
        this.options = options;
        this.loading = false;
      });
    },

    handler(value) {
      this.role.privileges = value;
    },

    // 保存角色权限信息
    authorizationHandler() {
      if (this.role.privileges.length == 0) {
        this.role.privileges = "";
      }
      let temp = { ...this.role };
      temp.role_id=temp.id;
      let temp1 = temp.privileges.join().split(",");
      let temp2 = Array.from(new Set(temp1));
      temp.privileges = temp2;
      post("/role/setPrivilege", temp).then(res => {
        this.$message({
          type: "success",
          message: res.message
        });
        this.authorization_visible = false;
        this.getDeviceList();
      });
    },
    // 递归去除权限中的空children
    foo(privileges) {
      for (const p of privileges) {
        if (p.children && p.children.length === 0) {
          delete p.children;
        } else {
          this.foo(p.children);
        }
      }
    },
    
    // //重置校验
    // resetForm(formName) {
    //   this.$refs[formName].resetFields();
    // },
  },
};
</script>
<style lang="scss" scoped>
.device {
  padding: 5px;
  .header {
    margin-bottom: 10px;
  }
}
</style>